package basis.game.shape;

import basis.game.main.Renderable;
import java.awt.Graphics2D;
import java.awt.Shape;
import static java.lang.Math.*;

public class Polygon2D implements Renderable{

    private double x,y,w,h,cx,cy,angle;
    private Line2D[] lines;
    private boolean show=true;
    
    public Polygon2D(double x[],double y[]){
        lines=new Line2D[x.length];
        for(int i=0;i<x.length-1;i++){
            lines[i]=new Line2D(x[i],y[i],x[i+1],y[i+1]);
        }
        lines[x.length-1]=new Line2D(x[x.length-1],y[x.length-1],x[0],y[0]);
        this.x=findLowest(x);
        this.y=findLowest(y);
        w=findHighest(x)-this.x;
        h=findHighest(y)-this.y;
        cx=this.x+w/2;
        cy=this.y+h/2;
    }
    
    private double findLowest(double[] p){
        double aa=p[0];
        for(int i=1;i<p.length;i++){
            if(aa>p[i]){
                aa=p[i];
            }
        }
        return aa;
    }
    
    private double findHighest(double[] p){
        double aa=p[0];
        for(int i=1;i<p.length;i++){
            if(aa<p[i]){
                aa=p[i];
            }
        }
        return aa;
    }
    
    public void setAngle(double a){
        double aa=a-this.angle;
        this.angle=a;
        double angle,length,na;
        for(int i=0;i<lines.length;i++){
            Line2D l=lines[i];
            length=sqrt(pow(l.x1-cx,2)+pow(l.y1-cy,2));
            angle=atan2(l.y1-cy,l.x1-cx);
            na=angle+aa;
            l.x1=cx+length*cos(na);
            l.y1=cy+length*sin(na);
            length=sqrt(pow(l.x2-cx,2)+pow(l.y2-cy,2));
            angle=atan2(l.y2-cy,l.x2-cx);
            na=angle+aa;
            l.x2=cx+length*cos(na);
            l.y2=cy+length*sin(na);
        }
    }
    
    @Override
    public void setX(double x) {
        move(x-this.x,0);
    }

    @Override
    public void setY(double y) {
        move(0,y-this.y);
    }

    @Override
    public void show(boolean s) {
        show=s;
    }

    @Override
    public void move(double x,double y) {
        this.x+=x;
        this.y+=y;
        cx+=x;
        cy+=y;
        for(int i=0;i<lines.length;i++){
            lines[i].x1+=x;
            lines[i].x2+=x;
            lines[i].y1+=y;
            lines[i].y2+=y;
        }
    }

    @Override
    public void update(long t) {
        
    }

    @Override
    public void render(Graphics2D g) {
        for(Line2D l:lines){
            g.draw(new java.awt.geom.Line2D.Double(l.x1,l.y1,l.x2,l.y2));
        }
    }

    @Override
    public double getX() {
        return x;
    }

    @Override
    public double getY() {
        return y;
    }

    @Override
    public boolean isShown() {
        return show;
    }

    @Override
    public Shape getBounds() {
        return null;
    }
    
    
    
}